package com.ptswitch.material.service.impl;

import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.hxzon.project.AbstractModelService;
import org.hxzon.util.StringUtil;
import org.springframework.stereotype.Service;

import com.ptswitch.material.model.contract.ContractItem;
import com.ptswitch.material.service.ContractItemService;

@Service
public class ContractItemServiceImpl extends AbstractModelService<ContractItem> implements ContractItemService {

    public List<ContractItem> findAll(long first, long size) {
        return dao.findList(ContractItem.class, " order by p.createTime desc ", first, size);
    }

    public List<ContractItem> findByExamine(String id, boolean pass) {
        if (pass) {
            return dao.findList(ContractItem.class, " where p.numPass=p.numReceiving and p.contract.id='" + id + "'");
        } else {
            return dao.findList(ContractItem.class, " where p.numPass!=p.numReceiving and p.contract.id='" + id + "'");
        }
    }

    public List<ContractItem> findByReceiving(String id, boolean receiving) {
        if (receiving) {
            return dao.findList(ContractItem.class, " where p.numReceiving =p.quantities and p.contract.id='" + id + "'");
        } else {
            return dao.findList(ContractItem.class, " where p.numReceiving !=p.quantities and p.contract.id='" + id + "'");
        }
    }

    public List<ContractItem> findByReturn(String id) {
        return dao.findList(ContractItem.class, " where p.numPass!=p.numReceiving and p.contract.id='" + id + "'");
    }

    public List<ContractItem> findByContract(String id) {
        return dao.findList(ContractItem.class, " where p.contract.id='" + id + "'");
    }

    public boolean existContractItemCode(ContractItem item) {
        ContractItem result = dao.findOne(ContractItem.class, " where p.contract.id='" + item.getContract().getId() + "' and p.code='" + item.getCode() + "'");
        return result != null;
    }

    private Pattern p = Pattern.compile(".*-\\d*-(\\d*)");

    public String emptyCode(String code) {
        code = StringUtil.escapeSql(code);
        List<String> list = (List<String>) dao.query("select p.code from ContractItem as p where p.code like '" + code + "-%' order by p.code", -1, -1);// code-%
        if (list.isEmpty()) {
            return code + "-1";
        }
        String lastCode = list.get(list.size() - 1);
        logger.debug("get empty code:{}", lastCode);
        Matcher m = p.matcher(lastCode);
        try {
            m.matches();
            int index = Integer.parseInt(m.group(1)) + 1;
            return code + "-" + index;
        } catch (RuntimeException e) {
            logger.error("get empty code fail", e);
        }
        return code;
    }

}
